﻿using PETimer;
using System;
using UnityEngine;

public class TickTimerExample2 : MonoBehaviour {
    public uint intervel = 66;
    public int count = 50;
    TickTimer timer;
    private void Start()
    {
        //timer = new TickTimer(0, false);
        timer = new TickTimer(0, true);
    }

    int sum = 0;
    int tid;
    void Update() {
        //外部线程驱动
        timer.UpdateTask();
        //4.可设置外部线程回调处理）
        timer.HandleTask();

        if(Input.GetKeyDown(KeyCode.A)) {
            DateTime historyTime = DateTime.UtcNow;
            tid = timer.AddTask(intervel,
                (int tid) => {
                    DateTime nowTime = DateTime.UtcNow;
                    TimeSpan ts = nowTime - historyTime;
                    historyTime = nowTime;
                    int delta = (int)(ts.TotalMilliseconds - intervel);
                    Extension.Log($"间隔差：{delta}");
                    sum += Math.Abs(delta);

                    Extension.Log($"tid:{tid} work.");
                },
                (int tid) => {
                    Extension.Log($"tid:{tid} work.");
                }, count);
        }

        if(Input.GetKeyDown(KeyCode.Delete)) {
            timer.DeleteTask(tid);
        }

        if(Input.GetKeyDown(KeyCode.S)) {
            Extension.Log("平均间隔：" + sum * 1.0F / count);
        }
    }
}
